package com.colter.project.sample.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeoutException;

/**
 * @author liangchao03
 * @date 2017/8/3
 */
public class RabbitMQ {
    private static String QUEUE_NAME = "my rabbit queue";

    public static void main(String[] args) throws IOException, TimeoutException {
//        new Run("a").start();
//        new Run("b").start();
//        new Run("c").start();
//        new Run("d").start();
   producer();


    }

    public static void consumer() throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println(" [x] Received '" + message + "'" + Thread.currentThread().getName());
            }
        };
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }

    public static void producer() throws IOException, TimeoutException {
        //factory.setUri("amqp://userName:password@hostName:portNumber/virtualHost");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername("guest");
        factory.setPassword("guest");
        //       factory.setVirtualHost("127.0.0.1");
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        Connection conn = factory.newConnection();
        Channel channel = conn.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        for (int i = 0; i < 500; i++) {
            channel.basicPublish("", QUEUE_NAME, null, ("Rabbit MQ !" + i).getBytes());
        }
        System.out.println("Done.");
        channel.close();
        conn.close();
    }

    static class Run extends Thread {
        public Run(String name) {
            super(name);
        }

        @Override
        public void run() {
            try {
                int result = new Random().nextInt(30) * 100;
                System.out.println(result);
                Thread.sleep(result);
                consumer();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

